#include "owi.h"



void TimerSetup(void){
	TCCR1A = 0;
	TCCR1B = (1 <<WGM12)|(5 << CS10);
	OCR1A = 0x1C1F;
	TIMSK = (1 <<OCIE1A);
}


void TimerStop(void) {	
	TIMSK = (0 <<OCIE1A);
}

ISR(TIMER1_COMPA_vect){
	Reset();
	Write_Instruction(0xEE);	
			
	//Reset
	Reset();

	// Read Temperature
	Write_Instruction(0xAA);
				
	printf("The current temperature is: %u degrees celcius\n",Read_Temperature());
}

 
void Reset(void) {

	//Set Port C to output
	DDRC = 0xFF;

	//Issue master reset pulse
	PORTC = 0x00;

	//Output 0 for 500us for master reset
	_delay_us(500);

	//Release and wait for presence pulse 
	DDRC = 0x00;
	_delay_us(500);

		
}



void Write_Instruction(char data) {
	uint8_t bit = 0;
	for (bit = 0; bit < 8; bit++) {
		if (data & (1 << bit)){
			// if a bit is a one then output the one pulse 
			DDRC = 0xFF;							
			PORTC = 0x00;						 
			_delay_us(5);

			PORTC = 0xFF;
			DDRC = 0x00;						  
			_delay_us(60);						  
		}
		else {
			// otherwise then output the zero pulse 
			DDRC = 0xFF;	//output						
			PORTC = 0x00;	//set to 0					 
			_delay_us(60);	// start time period
													  		
			PORTC = 0xFF;
			DDRC = 0x00;
			_delay_us(5);	// delay for rise time
		}
	}

}

unsigned int Read_Temperature(void){

	unsigned int read_value = 0;
	for (uint8_t i = 0; i < 8; i++)	{

		DDRC = 0xFF;
		PORTC = 0x00;
		_delay_us(5);
		PORTC = 0xFF;
		DDRC = 0x00;
		_delay_us(5);
	

		//Shift bit accross
		read_value = read_value >> 1;
		
		//Save value to byte
		if(PINC & 0x80)
		{
			read_value |= 0x80;
		}
		else
		{
			read_value |= 0x00;
		}
		
		_delay_us(50);
	}

	return read_value;
}



